package com.szewec.ps.myview;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.szewec.ps.R;
import com.szewec.ps.base.ListBaseAdapter;
import com.szewec.ps.base.SuperViewHolder;
import com.szewec.ps.model.CheckBoxValue;
import com.szewec.ps.model.Meta;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.project.ProjectListModel;
import com.szewec.ps.model.task.TaskListModel;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.task.TaskEditActivity;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.Constants;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;

/**
 * 选择对话框
 * <p>
 * Author: nanchen
 * Email: liushilin520@foxmail.com
 * Date: 2017-03-22  11:38
 */

public class BottomShowSelectProject extends Dialog implements OnClickListener, OnItemClickListener {

    private SelectDialogListener mListener;
    private Activity mActivity;
    private Button mMBtn_Cancel;
    private TextView mTv_Title;
    private List<String> mName;
    private String mTitle;
    private DataAdapter mDataAdapter;


    private List<ProjectListModel.ProjectModel> dataSource = new ArrayList<>();
    private LRecyclerView _lRecyclerView;
    private TextView tv_ensure;
    private int selectedItem = -1;
    //总条数
    private Integer TOTAL_COUNTER = -1;
    //页码
    private Integer _pageIndex = 1;
    //每页的条数
    private Integer _pageSize = 99999;

    private ClickCallBack _mClickCallBack;

    public interface SelectDialogListener {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id);
    }

    public interface ClickCallBack {
        void onItemClick(int position);
    }


    /**
     * 取消事件监听接口
     */
    private SelectDialogCancelListener mCancelListener;

    public interface SelectDialogCancelListener {
        public void onCancelClick(View v);
    }

    public BottomShowSelectProject(Activity activity, int theme,
                                   SelectDialogListener listener, List<String> names, ClickCallBack clickCallBack) {
        super(activity, theme);
        mActivity = activity;
        mListener = listener;
        this.mName = names;

        this._mClickCallBack = clickCallBack;

        setCanceledOnTouchOutside(true);
    }

    /**
     * @param activity       调用弹出菜单的activity
     * @param theme          主题
     * @param listener       菜单项单击事件
     * @param cancelListener 取消事件
     * @param names          菜单项名称
     */
    public BottomShowSelectProject(Activity activity, int theme, SelectDialogListener listener, SelectDialogCancelListener cancelListener, List<String> names) {
        super(activity, theme);
        mActivity = activity;
        mListener = listener;
        mCancelListener = cancelListener;
        this.mName = names;

        // 设置是否点击外围不解散
        setCanceledOnTouchOutside(false);
    }

    /**
     * @param activity 调用弹出菜单的activity
     * @param theme    主题
     * @param listener 菜单项单击事件
     * @param names    菜单项名称
     */
    public BottomShowSelectProject(Activity activity, int theme, SelectDialogListener listener, List<String> names) {
        super(activity, theme);
        mActivity = activity;
        mListener = listener;
        this.mName = names;

        // 设置是否点击外围可解散
        setCanceledOnTouchOutside(true);
    }

    public BottomShowSelectProject(Activity activity, int theme, SelectDialogListener listener, SelectDialogCancelListener cancelListener, List<String> names, String title) {
        super(activity, theme);
        mActivity = activity;
        mListener = listener;
        mCancelListener = cancelListener;
        this.mName = names;
        mTitle = title;

        // 设置是否点击外围可解散
        setCanceledOnTouchOutside(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = getLayoutInflater().inflate(R.layout.view_dialog_select_proj,
                null);

        // 获取下拉列表视图
        _lRecyclerView = view.findViewById(R.id.l_recycler_view);
        tv_ensure = view.findViewById(R.id.ensure);
        // 点击取消按钮
        view.findViewById(R.id.cancel).setOnClickListener((view1 -> dismiss()));
        // 点击确定按钮
        tv_ensure.setOnClickListener((view1 -> toConfirm()));

        setContentView(view, new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        Window window = getWindow();
        // 设置显示动画
        assert window != null;
        window.setWindowAnimations(R.style.main_menu_animstyle);

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = mActivity.getWindowManager().getDefaultDisplay().getHeight();

        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = LayoutParams.MATCH_PARENT;
        wl.height = LayoutParams.WRAP_CONTENT;
        window.getDecorView().setPadding(0, 0, 0, 0);

        // 设置显示位置
        onWindowAttributesChanged(wl);

        initRecycleView();
        getListDataFromServer();
    }

    private void showEnsure() {
        tv_ensure.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        dismiss();
        Log.v("底部弹出框：", "on click...");
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        mListener.onItemClick(parent, view, position, id);
        dismiss();
    }

    /**
     * 点击确认,跳转新建项目页面
     */
    private void toConfirm() {
        if (selectedItem < 0) {
            BamToast.showText(getContext(), "请选择项目");
            return;
        }
        Intent intent = new Intent(getContext(), TaskEditActivity.class);
        Log.i("toConfirm", JSONObject.toJSONString(dataSource.get(selectedItem)));
        // 组装传递对象
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("projectModel", dataSource.get(selectedItem));
        paramMap.put("taskVO", new TaskListModel.TaskVO());
        PresentValue<Map<String, Object>> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, paramMap);
        intent.putExtra(Constants.PRESENT_VALUE, presentValue);
        mActivity.startActivityForResult(intent, PreferincesContext.REQUEST_CODE);
        dismiss();
    }

    /**
     * 查询项目列表
     */
    private void getListDataFromServer() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("pageIndex", _pageIndex);
        param.put("pageSize", _pageSize);
        OkHttp.get("/tpms-plan-service/api/project/select", param, null, (result -> {
            ProjectListModel listModel = JSONObject.parseObject(result, ProjectListModel.class);
            Meta metaBean = listModel.getMeta();
            TOTAL_COUNTER = metaBean.getTotal() != null ? metaBean.getTotal() : -1;
            if (_pageIndex == 1) {
                dataSource.clear();
            }
            dataSource.addAll(listModel.getData());
            Log.i(TAG + "dataSource", JSONObject.toJSONString(dataSource));

            mDataAdapter.setDataList(dataSource);

            _lRecyclerView.refreshComplete(TOTAL_COUNTER);
        }));
    }

    /**
     * 初始化适配器
     */
    private void initRecycleView() {
        //初始化项目列表适配器
        mDataAdapter = new DataAdapter(getContext());
        mDataAdapter.addAll(dataSource);
        _lRecyclerView.setAdapter(new LRecyclerViewAdapter(mDataAdapter));
        _lRecyclerView.setHasFixedSize(true);
        _lRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        _lRecyclerView.setLoadMoreEnabled(false);
        _lRecyclerView.setPullRefreshEnabled(true);

        //设置底部加载文字提示
        _lRecyclerView.setFooterViewHint(getContext().getResources().getString(R.string.try_loading), getContext().getResources().getString(R.string.no_more_data), getContext().getResources().getString(R.string.no_more_data));
        _lRecyclerView.setArrowImageView(R.drawable.pulltorefresh_pulldown_refresh);
        _lRecyclerView.setOnRefreshListener(() -> {
            //重新初始化相关数据
            dataSource.clear();
            getListDataFromServer();
        });
    }


    private class DataAdapter extends ListBaseAdapter<ProjectListModel.ProjectModel> {

        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_project_add_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            ProjectListModel.ProjectModel model = mDataList.get(position);
            // 填充项目名称
            TextView tvProjectName = holder.getView(R.id.tv_project_name);
            tvProjectName.setText(TextViewUtil.convertDataString(model.getProjectName()));
            // 单选按钮
            ImageView ivRadio = holder.getView(R.id.iv_radio);
            if (selectedItem == position) {
                ivRadio.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_checkbox_circular_active));
            } else {
                ivRadio.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_checkbox_circular_passive));
            }
            //行点击监听事件
            holder.itemView.setOnClickListener(view -> {
                // 选中项目时，显示右上角的“确定”按钮
                showEnsure();
                if (selectedItem != position) {//增加限制条件，防止重复点击
                    selectedItem = position;
                    mDataAdapter.notifyDataSetChanged();
                }
            });

        }
    }
}
